package com.mentalhealthplatform.studentV3.controller;

import com.mentalhealthplatform.appModels.CustomUserDetails;
import com.mentalhealthplatform.appModels.Message;
import com.mentalhealthplatform.appModels.Reply;
import com.mentalhealthplatform.studentV3.service.MessageServiceV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v3/messages")
public class MessageControllerV3 {

    @Autowired
    private MessageServiceV3 messageServiceV3;

    // 学生端 - 创建新的留言
    @PostMapping
    public ResponseEntity<Message> createMessage(@RequestBody Message message) {
        // 获取当前登录用户的信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof CustomUserDetails userDetails) {
            UUID studentId = userDetails.getStudentId();
            message.setStudentId(studentId);
        }

        // 检查留言内容是否为空
        if (message.getContent() == null || message.getContent().isEmpty()) {
            throw new RuntimeException("留言内容不能为空");
        }

        // 设置当前时间为留言时间戳
        message.setCreatedAt(LocalDateTime.now());

        Message savedMessage = messageServiceV3.saveMessage(message);
        return ResponseEntity.status(201).body(savedMessage);
    }

    // 学生端 - 获取学生的所有留言及回复
    @GetMapping
    public ResponseEntity<List<Message>> getMessages(@RequestParam UUID studentId) {
        List<Message> messages = messageServiceV3.getMessagesByStudentId(studentId);
        System.out.println("返回的留言数据: " + messages);
        return ResponseEntity.ok(messages);
    }


    // 学生端 - 获取特定留言的所有回复
    @GetMapping("/{messageId}/replies")
    public ResponseEntity<List<Reply>> getReplies(@PathVariable Long messageId) {
        List<Reply> replies = messageServiceV3.getRepliesByMessageId(messageId);
        return ResponseEntity.ok(replies);
    }

    // 如果 content 为空，将会抛出 MethodArgumentNotValidException
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        return ResponseEntity.badRequest().body(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }
}
